import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus';
import { Result, ResultError } from '@/types';
import { getArrayColumnByKey } from './data/array';

export const getCookies = (key: string) => {
    return Cookies.get(key)
}

export const setStorage = (key: string, value: any, time = 0) => {
    localStorage.setItem(key, JSON.stringify({ data: value, time: time == 0 ? -1 : (new Date().getTime() + time * 1000) }))
}

export const getStorage = (key: string) => {
    let data = localStorage.getItem(key)
    if (!data) return null
    let dataObj = JSON.parse(data)
    if (dataObj.time != -1 && dataObj.time < new Date().getTime()) {
        localStorage.removeItem(key)
        return null
    } else {
        return dataObj.data
    }
}

export const errorMsg = (res: ResultError) => {
    if (res.code == 'SERVER_ERRPR') {
        let message = '';
        ElMessage({
            message: res?.data?.message || '服务器请求错误，请稍后再试',
            grouping: true,
            type: 'error',
        })
    } else if (res.code == 'ERRPR') {
        ElMessage({
            message: res?.data?.message || '未知错误',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    } else if (res.code == ' ERRPR_AUTH') {
        ElMessage({
            message: res?.data?.message || '未知错误',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    } else if (typeof res == 'string') {
        ElMessage({
            message: res || '处理失败!',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    }
}

export const successMsg = (res: Result | string) => {
    if (typeof res == 'string') {
        ElMessage({
            message: res,
            grouping: true,
            type: 'success',
            duration: 1500
        })
    } else if (typeof res == 'object') {
        ElMessage({
            message: res?.message || '处理成功！',
            grouping: true,
            type: 'success',
            duration: 1500
        })
    }
}
export const copyDomText = (val: string): void => {
    // 获取需要复制的元素以及元素内的文本内容
    const text = val
    // 添加一个input元素放置需要的文本内容
    const input = document.createElement('input')
    input.value = text
    document.body.appendChild(input)
    // 选中并复制文本到剪切板
    input.select()
    document.execCommand('copy')
    // 移除input元素
    document.body.removeChild(input)
    successMsg('复制成功')
}

export const getGoodsSpecFormat = (specData: Array<{
    name: string,
    value: Array<{
        name:string;
        img?:string | undefined | unknown;
    }>
}>) => {
    var len = specData.length,names = getArrayColumnByKey(specData,'name'),attrs:Array<{
        name:string;
        img?:string | undefined | unknown;
    }> = [];
    if (len > 0) {
        if (len > 1) {
            attrs = specData[0]['value'];
            for (var i = 0; i < len - 1; i++) {
                var temp = attrs;
                attrs = [];
                temp.forEach ((item:{
                    name:string;
                    img?:string| undefined | unknown;
                }) => {
                    specData[i + 1].value.forEach((v:{
                        name:string;
                        img?:string | undefined | unknown;
                    })=>{
                        attrs.push({
                            name:item.name + ',' + v.name,
                            img:(item.img || '') + ',' + ( v.img || '')
                        })
                    })
                })
            }
        } else {
            specData[0].value.forEach ((item:{
                name:string;
                img?:string | undefined | unknown;
            }) => {
                attrs.push({
                    name:item.name,
                    img:item?.img || ''
                });
            })
        }
    }
    return {
        names,
        attrs
    }
}

export const staticImgPath = (path: string, source = 'assets') => {
    switch (source) {
      case 'assets':
        return new URL('/src/theme/image/' + path, import.meta.url).href
        break;
      default:
        return new URL('/static/common/image/' + path, import.meta.env.VITE_BASE_URL).href
        break;
    }
  }

export default {
    getCookies,
    setStorage,
    getStorage,
    errorMsg,
    successMsg,
    copyDomText,
    getGoodsSpecFormat,
    staticImgPath
}